using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using UnityEngine.Events;

//���������
public class ArrangeWindow : Window
{
    SkillDetailWindow skillWindow;
    GComponent skillSelectPanel;
    GComponent ruleSelectPanel;
    GComponent leftSelectPanel;
    GLoader[] loaders; //4个技能槽的图片
    GButton[] skillBtns; //4个技能槽按钮
    GButton[] baseBtns; //阵基按钮
    GObject[] baseHighLight;
    GButton refreshButton;
    GTextField[] baseTexts;

    GList ruleWaitSelectList;//阵眼里的法则选择列表（位置在阵眼下方）
    GList skillWaitSelectList; //技能选择列表（显示在右侧）
    GList ruleSelectList;//可选法则列表
    int currentSelectSkillId;
    int currentLoaderIndex = -1; //当前技能的索引所在格子索引
    int currentCampIndex = 0; //当前正在编辑的阵眼
    int currentRuleIndex = 0;//当前编辑法则ID
    GComponent tipPanel;
    public GComponent costPanel;

    GButton newCampBtn;
    GButton memoryBtn;
    GButton flagBtn;
    GButton runeBtn;
    Controller newBtnClick;
    Controller memeryBtnClick;
    Controller flagBtnClick;
    Controller runeBtnClick;

    string mode = "newCamp";

    public ArrangeWindow()
    {
    }

    public void setPos(Vector3 pos)
    {
        position = pos;
    }

    protected override void OnInit()
    {
        loaders = new GLoader[4];
        skillBtns = new GButton[4];
        baseBtns = new GButton[4];
        baseHighLight = new GObject[4];
        baseTexts = new GTextField[4];
        contentPane = UIPackage.CreateObject("CommonPackage", "arrange").asCom;
        leftSelectPanel = contentPane.GetChild("main1").asCom;
        //新的阵法，记忆按钮
        newCampBtn = leftSelectPanel.GetChild("newCampBtn").asButton;
        memoryBtn = leftSelectPanel.GetChild("memoryBtn").asButton;
        flagBtn = leftSelectPanel.GetChild("flagBtn").asButton;
        runeBtn= leftSelectPanel.GetChild("runeBtn").asButton;
        newBtnClick = newCampBtn.GetController("isClick");
        memeryBtnClick = memoryBtn.GetController("isClick");
        flagBtnClick = flagBtn.asButton.GetController("isClick");
        runeBtnClick = runeBtn.GetController("isClick");
        if (mode == "newCamp")
        {
            selectNewCampMode();
        }
        selectFlagMode();
        leftSelectPanel.GetChild("newCampBtn").onClick.Add(() => {
            selectNewCampMode();
        });

        leftSelectPanel.GetChild("memoryBtn").onClick.Add(() => {
            selectMemoryMode();
        });
        
        newCampBtn.onKeyDown.Add(selectNewCampMode);
        memoryBtn.onKeyDown.Add(selectMemoryMode);
        flagBtn.onClick.Add(selectFlagMode);
        runeBtn.onClick.Add(selectRuneMode);

        costPanel = contentPane.GetChild("costPanel").asCom;
        costPanel.GetChild("main").asCom.GetChild("quitButton").onClick.Add(hideSelf);
        costPanel.GetChild("main").asCom.GetChild("finishButton").onClick.Add(hideSelf);
        // tipPanel = UIPackage.CreateObject("CommonPackage", "tipPanel").asCom;
        this.Center();
        this.modal = true;
        getSkillBtns();
        getBaseUI();
        refreshButton = contentPane.GetChild("refreshButton").asButton;
        refreshButton.visible = false;
        skillSelectPanel = this.contentPane.GetChild("skillSelectPanel").asCom;

        ruleSelectPanel = this.contentPane.GetChild("ruleSelectPanel").asCom;
        skillWindow = new SkillDetailWindow();
        /*this.contentPane.GetChild("closeBtn").onClick.Add(() =>
        {
            this.Hide();
        });*/
        skillSelectPanel.GetChild("hideBtn").asButton.onClick.Add(hideSkillSelectPanel
        );
        ruleSelectPanel.GetChild("hideBtn").asButton.onClick.Add(hideRuleSelectPanel);


        skillSelectPanel.visible = false;
        ruleSelectPanel.visible = false;
        skillWaitSelectList = skillSelectPanel.GetChild("skillList").asList;
        ruleWaitSelectList = leftSelectPanel.GetChild("ruleList").asList;
        ruleSelectList = ruleSelectPanel.GetChild("list").asList;
        ruleSelectList.itemRenderer = RenderRuleCanSelectListItem;
        refreshRuleSeletcList();
        ruleWaitSelectList.itemRenderer = RenderRuleWaitSelectListItem;
        ruleWaitSelectList.SetVirtual();
        ruleWaitSelectList.numItems = 4;
        skillWaitSelectList.itemRenderer = RenderArrangeNotSelectSkillListItem;
        refreshNotSelectList();
        refreshRulenotSelectList();
        
        cancelHighlight();
        initCampUI();
        showCampInfo();
    }

    void selectFlagMode()
    {
        Debug.Log(44);
        flagBtnClick.SetSelectedIndex(1);
        runeBtnClick.SetSelectedIndex(0);
    }

    void selectRuneMode()
    {
        Debug.Log(33);
        flagBtnClick.SetSelectedIndex(0);
        runeBtnClick.SetSelectedIndex(1);
    }

    void selectNewCampMode()
    {
        newBtnClick.SetSelectedIndex(1);
        memeryBtnClick.SetSelectedIndex(0);
    }

    void selectMemoryMode()
    {
        newBtnClick.SetSelectedIndex(0);
        memeryBtnClick.SetSelectedIndex(1);
    }

    void hideSelf()
    {
        Hide();
        MainUI.GetInstance().hideArrangePanel();
    }
    void getSkillBtns()
    {
        for(int i = 0; i < 4; i++)
        {
            skillBtns[i] = leftSelectPanel.GetChild("skillBtn"+(i+1)).asButton;
            skillBtns[i].onClick.Add(() =>
            {
                skillSelectPanel.visible = true;
            });
            loaders[i] = skillBtns[i].GetChild("spriteLoader").asLoader;
            
                loaders[i].url = "";
            skillBtns[i].data = i;

            skillBtns[i].onClick.Add(showSkillSelectPanel);
            skillBtns[i].onRollOver.Add(hoverSelectItem);
            skillBtns[i].onRollOut.Add(rollOutSelectItem);
        }
    }

    void getBaseUI()
    {
        for (int i = 0; i < 4; i++)
        {
            baseBtns[i] = leftSelectPanel.GetChild("baseBtn" + (i + 1)).asButton;
            baseTexts[i] = leftSelectPanel.GetChild("baseText" + (i + 1)).asTextField;
            baseHighLight[i] = leftSelectPanel.GetChild("highlight" + (i + 1));
            baseHighLight[i].visible = false;
            
        }
        for (int x = 0; x < 4; x++)
        {
            baseBtns[x].data = x;
            baseBtns[x].onRollOver.Add((EventContext context) => {
                int index = (int)(context.sender as GObject).data;
                cancelBaseHightLight();
                baseHighLight[index].visible = true;
            });
            baseBtns[x].onRollOut.Add(() => {
                cancelBaseHightLight();
                baseHighLight[currentCampIndex].visible = true;
            });
        }
    }

    //初始化阵眼UI
    void initCampUI()
    {
        int i = 0;
        foreach (var camp in DataManager.GetInstance().campbases)
        {
            baseTexts[i].text = camp.skillNum + "\n" + camp.ruleNum;
            baseBtns[i].data = i;
            baseBtns[i].onClick.Add(showCampInfo);
           
            i++;
        }
       

    }

    //刷新待选择技能列表
    void refreshNotSelectList()
    {
        skillWaitSelectList.numItems = 6;
    }

    //刷新已选选法则列表
    void refreshRulenotSelectList()
    {
        ruleWaitSelectList.numItems = 8;
    }

    //刷新可选法则列表（弹窗里的）
    void refreshRuleSeletcList()
    {
        ruleSelectList.numItems = 3;
    }

    void hideDetailPanel()
    {
        skillWindow.Hide();
    }

    //取消阵眼高光
    void cancelHighlight()
    {
        foreach (var btn in skillBtns)
        {
            btn.GetChild("highlight").visible = false;
        }
       
    }

    void cancelBaseHightLight()
    {
        for (int i = 0; i < 3; i++)
        {
            baseHighLight[i].visible = false;
        }
    }

    void cancelRulelight()
    {
        foreach (var btn in ruleWaitSelectList.GetChildren())
        {
            btn.asCom.GetChild("highlight").visible = false;
        }
    }

    void RenderArrangeNotSelectSkillListItem(int index, GObject obj)
    {
        GButton button = obj.asButton;
        button.title = "" + index;
        obj.asCom.visible = false;
        obj.asCom.GetChild("highlight").visible = false;
        GLoader spriteLoader1 = button.GetChild("skillIcon").asLoader;
        List<int> notSelectIds = new List<int>();
        spriteLoader1.url = "";
        int id;
        // SkillItem skill = DataManager.GetInstance().skillInfos.Find(x => x.id == id);
         CampBase camp = DataManager.GetInstance().campbases[currentCampIndex];
        if(index< DataManager.GetInstance().skillInfos.Count){
            SkillItem skill=DataManager.GetInstance().skillInfos[index];
        
             id = skill.id;
            
             if (camp.skillPoses.Find(x=>x == id) == id)
             {
                button.GetChild("highlight").visible = true;
                button.GetChild("selectedText").visible = true;
             } else {
                 button.GetChild("selectedText").visible = false;
                button.GetChild("highlight").visible = false;
            }
            SelectSkill tmp = new SelectSkill();
            tmp.id = id;
            tmp.index = index;
            button.data = tmp;

            button.onRollOver.Add(hoverItem);
            button.onRollOut.Add(rollOutItem);
           
            if (skill != null)
            {
                obj.asCom.visible = true;
                button.GetChild("nameText").text = skill.name;
                button.GetChild("descText").text = skill.desc;
                spriteLoader1.url = "ui://Sprites/" + skill.icon;
            }

        button.onClick.Add(chooseSkill);
        }
         
    }

    //显示可选择法则列表
    void RenderRuleCanSelectListItem(int index, GObject obj)
    {

        GButton button = obj.asButton;
        button.title = "" + index;
        button.data = index;
        List<int> notSelectIds = new List<int>();
        CampBase camp = DataManager.GetInstance().campbases[currentCampIndex];
        button.GetChild("highlight").visible = false;
        /* foreach (var item in DataManager.GetInstance().ruleInfos)
         {*/
        /*if (!DataManager.GetInstance().arrangeSkillIds.Contains(item.id))
        {
            notSelectIds.Add(item.id);
        }*/
        //Debug.Log(item.id);
        RuleItem item = DataManager.GetInstance().ruleInfos[index];
        int id = item.id;
        if (camp.ruleIds.Find(x => x == id) == id)
        {

            button.GetChild("selectedText").visible = true;
            button.GetChild("highlight").visible = true;
        } else
        {
            button.GetChild("highlight").visible = false;
            button.GetChild("selectedText").visible = false;

        }
        
            
            button.data = id;
            
            RuleItem rule = DataManager.GetInstance().ruleInfos.Find(x => x.id == id);
            if (rule != null)
            {
                //button.GetChild("highlight").visible = true;
                Debug.Log(rule.ToString());
                obj.asCom.visible = true;
                button.GetChild("nameText").text = rule.name;
                button.GetChild("descText").text = rule.desc;
            }
            if(camp.ruleIds.Find(x=>x == id) !=id)
            {
            }
            button.onClick.Add(chooseRule);
            //notSelectIds.Add(item.id);
        //}
       
    }

    //刷新待选择法则列表
    void RenderRuleWaitSelectListItem(int index, GObject obj)
    {
        GButton button = obj.asButton;
        button.title = "" + index;
        button.data = index;
        CampBase camp = DataManager.GetInstance().campbases[currentCampIndex];
        button.GetChild("nameText").text = "";
        button.GetChild("disabledPic").visible = true;
        button.GetChild("ruleAddBtn").visible = true;
        GGroup showGroup = button.GetChild("showGroup").asGroup;
        showGroup.visible = false;
        if (index < camp.ruleNum)
        {
            showGroup.visible = true;
            
            button.GetChild("disabledPic").visible = false;
        } else
        {
            button.GetChild("ruleAddBtn").visible = false;
        }
        if (index < camp.ruleIds.Count)
        {
            int id = camp.ruleIds[index];
            button.GetChild("ruleAddBtn").visible = false;
            button.GetChild("highlight").visible = false;
            if (id > 0)
            {
                RuleItem rule = DataManager.GetInstance().ruleInfos.Find(x => x.id == id);
                if (rule != null)
                {
                    button.GetChild("nameText").text = rule.name;
                    button.GetChild("addBtn").visible = false;
                }
            }
        }

        button.onClick.Add(showRuleChoosePanel);
    }

    void rollOutItem()
    {
        skillWindow.Hide();
      

    }

    void hideRefreshBtn()
    {
        if (!ruleSelectPanel.visible && !skillSelectPanel.visible)
        {
            refreshButton.visible = false;
        }
    }


    void hideSkillSelectPanel()
    {
        skillSelectPanel.visible = false;
        hideRefreshBtn();
    }

    void hideRuleSelectPanel()
    {
        ruleSelectPanel.visible = false;
        hideRefreshBtn();
    }

    //显示选择技能面板
    void showSkillSelectPanel(EventContext context)
    {
        refreshButton.visible = true;
        currentLoaderIndex = (int)(context.sender as GObject).data;
        refreshNotSelectList();
        skillSelectPanel.visible = true;
        cancelHighlight();
        skillBtns[currentLoaderIndex].GetChild("highlight").visible = true;

    }

    //显示法则选择面板
    void showRuleChoosePanel(EventContext context)
    {
        refreshButton.visible = true;
        currentRuleIndex = (int)(context.sender as GObject).data;
        //cancelRulelight();
        refreshRuleSeletcList();
        ruleWaitSelectList.GetChildAt(currentRuleIndex).asCom.GetChild("highlight").visible = true;
        ruleSelectPanel.visible = true;
    }

    override protected void DoShowAnimation()
    {
        this.SetScale(0.1f, 0.1f);
        this.SetPivot(0.5f, 0.5f);
        this.TweenScale(new Vector2(1, 1), 0.3f).OnComplete(this.OnShown);
    }

    override protected void DoHideAnimation()
    {
        this.TweenScale(new Vector2(0.1f, 0.1f), 0.3f).OnComplete(this.HideImmediately);
    }

    void hoverItem(EventContext context)
    {

       
        //GButton item = (GButton)context.data;
        //item.GetChild("highlight").visible = true;
        GObject obj = GRoot.inst.touchTarget;
        if (obj != null)
        {

            //obj.asCom.GetChild("highlight").visible = true;
            // Vector2 v2 = obj.LocalToGlobal(new Vector2(obj.x, obj.y));
            // skillWindow.x = v2.x + obj.width -50;
            // skillWindow.y = v2.y-obj.height/2;
            // skillWindow.Show();
        }
    }

    void hoverSelectItem(EventContext context)
    {
        int index = (int)((context.sender as GObject).data);

        //GObject obj = GRoot.inst.touchTarget;
        GObject obj = context.sender as GObject;
        if (obj != null && loaders[index].url != "")
        {
            Vector2 v2 = new Vector2(obj.x, obj.y);
            skillWindow.x = v2.x + obj.width - 50;
            skillWindow.y = v2.y - obj.height / 2;

            skillWindow.Show();

        }
        obj.asCom.GetChild("highlight").visible = true;

    }


    void rollOutSelectItem()
    {
        skillWindow.Hide();
        cancelHighlight();
    }


    //选择技能
    void chooseSkill(EventContext context)
    {
        int chooseSkillId = ((SelectSkill)((context.sender as GObject).data)).id;
        CampBase camp = DataManager.GetInstance().campbases[currentCampIndex];
        Debug.Log(camp.ToString());
        Debug.Log(currentCampIndex + "_" + currentLoaderIndex + "_" + chooseSkillId);
        if (currentLoaderIndex == -1 || camp.skillPoses.Find(x => x == chooseSkillId) == chooseSkillId)
        {
            camp.skillPoses.RemoveAll(x => x == chooseSkillId);
        } else
        {
            DataManager.GetInstance().addSkillByCamp(currentCampIndex, currentLoaderIndex, chooseSkillId);
        }
        
        
        refreshChooseSkillList(camp);
        refreshNotSelectList();
    }

    void refreshChooseSkillList(CampBase camp)
    {
        foreach (var loader in loaders)
        {
            loader.url = "";
        }
        
        for (int i = 0; i < camp.skillPoses.Count; i++)
        {
            int id = camp.skillPoses[i];
            SkillItem skill = DataManager.GetInstance().skillInfos.Find(x=>x.id ==id);
            if (skill != null) {
                Debug.Log(skill.icon);
                loaders[i].url = "ui://Sprites/" + skill.icon + "_big";
            }
            
        }
    }

    //选择法则
    void chooseRule(EventContext context)
    {
        int chooseRuellId = (int)(context.sender as GObject).data;
        CampBase camp = DataManager.GetInstance().campbases[currentCampIndex];
        /*if (currentRuleIndex == -1 || camp.ruleIds.Find(x => x.id == chooseRuellId) != null)
        {
            return;
        }*/
        Debug.Log(currentCampIndex + "-" + currentRuleIndex + "-" + chooseRuellId);
        if(camp.ruleIds.Contains(chooseRuellId)){
            camp.ruleIds.RemoveAll(x => x == chooseRuellId);
        } else
        {
            DataManager.GetInstance().addRuleByCamp(currentCampIndex, currentRuleIndex, chooseRuellId);
        }
        
        //ruleSelectPanel.visible = false;
        refreshRuleSeletcList();
        refreshRulenotSelectList();

    }

    /// <summary>
    /// 显示当前阵信息
    /// </summary>
    void showCampInfo(EventContext context = null)
    {
        int index;
        if (context == null)
        {
            index = 0;
        }
        else
        {
            index = (int)(context.sender as GObject).data;
        }
        cancelBaseHightLight();
        cancelHighlight();
        cancelRulelight();
        if (baseHighLight[index] != null)
        {
            baseHighLight[index].visible = true;
        }
        skillSelectPanel.visible = false;
        ruleSelectPanel.visible = false;
        currentCampIndex = index;
        currentLoaderIndex = -1;
        CampBase camp = DataManager.GetInstance().campbases[index];
        Debug.Log(camp.ToString());
        foreach (var btn in skillBtns)
        {
            btn.visible = false;
        }
        for(int i = 0; i < camp.skillNum; i++)
        {
            skillBtns[i].visible = true;
        }
        hideRefreshBtn();
        refreshChooseSkillList(camp);
        ruleSelectList.numItems = ruleSelectList.numItems;
        ruleWaitSelectList.numItems = 8;
    }

  
}




public class SelectSkill
{
    public int id; //.װ��ID
    public int index; //װ������

}
